import React, { Component } from "react";
import PageTitle from "../../components/page-title/index.jsx";
import "./index.scss";
import Mutil from "util/mim.jsx";
import User from "server/user-server.jsx";

const user = new User();
const mm = new Mutil();

export default class Login extends Component {
  constructor(props) {
    super(props);
    this.state = {
      username: "",
      password: "",
      redirect: mm.getUrlParam("redirect") || "/"
    };
  }
  inputChange(e) {
    // console.log(e.target.value);
    let inputValue = e.target.value;
    let inputName = e.target.name;
    this.setState({
      [inputName]: inputValue
    });
  }
  inputKeyChange(e){
    if(e.keyCode === 13){
      this.onsubmit()
    }
  }
  // 用户提交表单
  onsubmit() {
    let loginInfo = {
      username: this.state.username,
      password: this.state.password
    };
    let checkResult = user.checkLoginInfo(loginInfo);
    if (checkResult.status) {
      user.login(loginInfo).then(
        res => {
          mm.setStorage('userInfo',res)
          this.props.history.push(this.state.redirect);
        },
        errMsg => {
          mm.errorTips(errMsg);
        }
      );
    }
    //验证信息不通过
    else{
      mm.errorTips(checkResult.msg)
    }
  }
  componentDidMount(){
    document.title = '登录-HAPPY 商城'
  }
  render() {
    return (
      <div className="col-md-4 col-md-offset-4">
        <div className="panel login-panel">
          <div className="panel-body">
            <div role="form">
              <legend>欢迎登录 -MMALL系统</legend>

              <div className="form-group">
                <input
                  name="username"
                  type="text"
                  className="form-control"
                  placeholder="用户名"
                  onChange={e => this.inputChange(e)}
                  onKeyUp={e => this.inputKeyChange(e)}
                />
              </div>
              <div className="form-group">
                <input
                  name="password"
                  type="password"
                  className="form-control"
                  placeholder="密码"
                  onChange={e => this.inputChange(e)}
                  onKeyUp={e => this.inputKeyChange(e)}
                />
              </div>
              <div className="form-group">
                <button
                  className="btn btn-lg btn-info btn-block "
                  onClick={e => {
                    this.onsubmit(e);
                  }}
                >
                  登录
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }
}
